import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'
import util from "@/utils/util"
import { reqestMethod } from './api'
import eventBus, { EventBusEmitType } from '@/utils/eventbus'
import { IResponseCodeType } from '@/models/common'

const service = axios.create({
  baseURL: '',
  timeout: 30000
})

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    let token = util.getToken();
    if (config.method == reqestMethod.POST) {
      if (config.headers) {
        if (util.isFormData(config.data)) {
          config.headers['Content-Type'] = 'multipart/form-data'
          config.data.append('token', token)
        }else{
          config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
          config.data = {
            "token": token,
            ...config.data
          }
        }
      }
    }
    if (config.method == reqestMethod.GET){
      config.params = {
        "token": token,
        ...config.params
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status !== 200) {
      response.statusText && util.alertTip(response.statusText)
      return Promise.reject(response)
    } else {
      if (response.data.code == IResponseCodeType.TokenExpired) {
        response.statusText && util.updateLoading('info', EventBusEmitType.OnGoToLogin, response.data.message, 2, () => {
          eventBus.emit(EventBusEmitType.OnGoToLogin)
        })
        return Promise.reject(response.data)
      } else {
        return response.data
      }
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service